// pages/refundOrder/refundOrder.js
Page({
    data: {
        orderId: '',
        orderPrice: 0,
        refundAmount: 0,
        isLoading: false
    },

    onLoad(options) {
        console.log(options);
        if (options.orderId && options.orderPrice) {
            this.setData({
                orderId: options.orderId,
                orderPrice: parseFloat(options.orderPrice)
            });
        } else {
            wx.showToast({
                title: '参数错误',
                icon: 'none'
            });
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
        }
    },

    // 输入退款金额
    onRefundAmountInput(e) {
        let amount = e.detail.value;
        amount = amount.replace(/[^\d.]/g, ''); // 只允许数字和小数点
        amount = parseFloat(amount).toFixed(2); // 保留两位小数
        console.log(parseFloat(amount));
        // 限制不超过订单金额
        if (parseFloat(amount) > this.data.orderPrice) {
            amount = this.data.orderPrice.toFixed(2);
        }

        this.setData({
            refundAmount: parseFloat(amount)
        });
    },

    // 提交退款申请
    submitRefund() {
        const {
            orderId,orderPrice,
            refundAmount
        } = this.data;

        if (!refundAmount || refundAmount <= 0) {
            wx.showToast({
                title: '请输入退款金额',
                icon: 'none'
            });
            return;
        }

        this.setData({
            isLoading: true
        });

        wx.cloud.callFunction({
            name: 'wxpayFunctions',
            data: {
                type: 'wxpay_refund',
                data: {
                    transaction_id: orderId, // 微信订单号
                    // transaction_id:"4200002664202506265613640309",
                    refund_amount: refundAmount * 100, // 退款金额(分)
                    total_amount: orderPrice * 100, // 原订单金额(分)
                }
            },
            success: (res) => {
                console.log(res);
                this.setData({
                    isLoading: false
                });

                if (res.result.data.status == 'PROCESSING') {

                    wx.showToast({
                        title: '退款申请已提交',
                        icon: 'success'
                    });

                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1500);
                } else {
                    wx.showToast({
                        title: res.result.message || '退款申请失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                this.setData({
                    isLoading: false
                });
                console.error('申请退款失败:', err);
                wx.showToast({
                    title: '系统错误，请重试',
                    icon: 'none'
                });
            }
        });
    }
});